package com.example.tuike.entity;

import com.example.tuike.common.utils.DateConverter;
import com.rometools.rome.feed.synd.SyndFeed;
import com.rometools.rome.io.SyndFeedInput;
import com.rometools.rome.io.XmlReader;

import java.net.URL;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/*** @Author supersaiya
 * @Description TODO

 * @Date 2025/2/5 18:27

 * @Version 1.0*/
public class RssFetcher {

    public static List<Contents> fetch(String rssUrl) {
        try {
            SyndFeed feed = new SyndFeedInput().build(new XmlReader(new URL(rssUrl)));
            Date feedPublishedDate = feed.getPublishedDate(); // 获取 feed 的发布日期
            LocalDateTime defaultPublishedAt = feedPublishedDate != null ? DateConverter.convertToLocalDateTime(feedPublishedDate) : null;
            return feed.getEntries().stream().map(entry -> {
                Contents content = new Contents();
                content.setTitle(entry.getTitle());
                content.setLink(entry.getLink());
                content.setContent(entry.getDescription().getValue());
                Date publishedDate = entry.getPublishedDate();
                LocalDateTime publishedAt = publishedDate != null ? DateConverter.convertToLocalDateTime(publishedDate) : defaultPublishedAt;
                content.setPublishedAt(publishedAt);
                return content;
            }).collect(Collectors.toList());
        } catch (Exception e) {
            // 处理异常并记录日志
            return Collections.emptyList();
        }
    }
}